<?php
error_reporting(0);
/**
 * Handles Sessions and Security
 * @name SessionControl
 * @author Joey Adams
 *
 */

class SessionControl
{


// Configuration
private $use_user_agent = true; // Use Users' User-Agent in fingerprint.
private $num_ip_digits = 3; // Number of Users' IP digits to include in fingerprint.
private $regenerate_id = true; // Constantly regenerate ID's to prevent attacks.
private $salt; // Randomly Generated String to include in fingerprint.
private $control_word = '_SALT_';  // Control Word to add to Fingerprint.


// Call Start Functions to create salt, and start the session.
function __construct()
    {
        @session_start();
    }

// Initialize Session and Create Fingerprint
public function Open()
    {
        $this->_intSalt();
        $_SESSION['fprint'] = $this->_Fingerprint();
        $this->_RegenerateId();
    }

// Check to see if Fingerprint is set
public function Check()
    {
    	$this->_RegenerateId();
   		return (isset($_SESSION['fprint']) && $_SESSION['fprint'] == $this->_Fingerprint('check'));
    }

// Create Randomly Generated Salt
private function _intSalt()
    {
        for($i=0;$i<10;$i++)
        {
            $grains[$i] = chr(rand(33,126));    
        }
        $this->salt = implode($grains);
        $_SESSION['salt_'] = $this->salt; 
    }

// Create Unique Fingerprint based on configuration    
private function _Fingerprint($mode=null)
    {
        if  ($mode == 'check') 
        { 
            $fingerprint = $_SESSION['salt_']; 
        } 
        else 
        { 
            $fingerprint = $this->salt; 
        }
        $fingerprint .= $this->control_word;
        if ($this->use_user_agent)
        {
            $fingerprint .= $_SERVER['HTTP_USER_AGENT'];
        }
        if ($this->num_ip_digits)
        {
            $ip_digits = abs(intval($this->num_ip_digits));
            if ($ip_digits > 4) 
            {
                $ip_digits = 3; 
            }
            $digits = explode('.', $_SERVER['REMOTE_ADDR']);
            for ($i=0; $i<$ip_digits; $i++)
            {
                $fingerprint .= $digits[$i] . '.';
            }
        }
        return md5($fingerprint);
    }

// Regenerate Session ID If Possible
private function _RegenerateId()
    {
        if ($this->regenerate_id && function_exists('session_regenerate_id'))
        {
            session_regenerate_id();
        }
    }
    
}